<template>
	<a-modal v-bind="options">
		<div class="invOrgs">
			<exclamation-circle-filled style="color: #faad14ff; margin-right: 10px" />
			<span style="color: red">{{ modelRef.tips }}</span>
			{{ props.type === 1 || props.type === 3 ? '若企业合同关联房间存在未搬离员工，员工将自动搬离' : null }}
		</div>

		<div class="flex-container-nomal" style="height: 70vh">
			<vxe-grid ref="grid" v-bind="gridOptions">
				<template #label="{row}">
					<a-tag v-if="row.label" :color="labelStatus[row.label]?.color" style="min-width: 70px">
						{{ labelStatus[row.label]?.name }}
					</a-tag>
					<template v-if="APPROVAL_STATUS_MAP[row.approvalStatus]">
						<a-tooltip destroy-tooltip-on-hide>
							<template #title>
								{{ APPROVAL_STATUS_MAP[row.approvalStatus].label }}
							</template>
							<svg-icon :icon-class="APPROVAL_STATUS_MAP[row.approvalStatus].icon" />
						</a-tooltip>
					</template>
				</template>
				<template #enterpriseName="{row}">
					<div>{{ row.enterPriseName }}</div>
				</template>
				<template #contract="{row}">
					<div>
						{{ SIGN_TYPE_MAP[row.signType] }}
						<span v-if="row.signType">/</span>
						{{ row.signEmpName }}
					</div>
					<div>
						{{ row.signTime }}
						<span v-if="row.signTime">/ 共</span>
						({{ row.signHouseCount }}间)
					</div>
				</template>
				<template #personal="{row}">
					<div>
						{{ desensitizationName(row.name) }}
						<span v-if="row.name">/</span>
						{{ desensitizationPhone(row.phone) }}
					</div>
				</template>
				<template #cycle="{row}">
					<div>
						{{ row.beginTime }}
						<span v-if="row.beginTime">~</span>
						{{ row.endTime }}
					</div>
					<div>
						租金{{ row.price }}
						<span v-show="row.price">元/月&nbsp;</span>

						押金{{ row.deposit }}元

						<span v-show="row.depositMonth">&nbsp;押</span>
						{{ row.depositMonth }}
						<span v-show="row.periodMonth?.length < 3">付</span>
						{{ row.periodMonth }}
					</div>
				</template>
				<template #action="{row}">
					<!-- 审批续租允许查看详情 -->
					<a v-if="!props.hideDetails || (contract.isApproval && type === 2)" @click="handlerClick(row, 0)">查看合同</a>
					<template v-if="props.type === 1">
						<a-divider type="vertical" v-if="!props.hideDetails" />
						<a @click="handlerClick(row, 1)">退租</a>
					</template>
				</template>
			</vxe-grid>
		</div>

		<template #footer>
			<a-row type="fixed" justify="end" v-if="props.type !== 1 && !contract.isApproval">
				<a-space :size="12">
					<a-button @click="options.onCancel">取消</a-button>
					<a-button type="primary" @click="confirm" :disabled="selections.length === 0">确定</a-button>
				</a-space>
			</a-row>
		</template>
	</a-modal>

	<charter-contract-details
		v-if="!props.hideDetails || (contract.isApproval && type === 2)"
		v-model:visible="visibles.showDetails"
		:id="(records.id as string)"
		:status="records.label"
		:approvalStatus="visibles.approvalStatus"
		:hideButton="true"
		:contract="contract"
		:isShowPrior="false"
		@close="close()" />

	<!-- 包租合同 续租 -->
	<signing-dialog
		v-model:visible="visibles.addCharter"
		:resubmitId="resubmitId"
		:signing-type="'charter'"
		@success="getListF"
		:approvalStatus="visibles.approvalStatus"
		:reletId="(reletId  as string)"
		:reletIds="reletIds" />

	<!-- 批量退租 -->
	<batch-retreat-rent
		:enter-prise-contract-id="records.id"
		v-model:visible="visibles.showRetreatRent"
		@success="getListF"
		:resubmitId="resubmitId" />

	<!-- 作废 -->
	<contracts-cancel v-model:visible="visibles.contractsCancel" :info="info" :contractIds="contractIds" @success="getListF" />
</template>

<script setup lang="ts">
	import {computed, reactive, ref, toRef, watch} from 'vue'
	import {VxeGridInstance, VxeGridProps} from 'vxe-table'
	import {DownOutlined, ExclamationCircleFilled} from '@ant-design/icons-vue'
	import {APPROVAL_STATUS_MAP, SIGN_TYPE_MAP} from '@/interface/contract'
	import {labelStatus} from '@/utils/charter-contract'
	import {getList, getBeforeRenewalList} from '@/api/charter-contract'
	import {desensitizationName, desensitizationPhone} from 'yuxin-base/src/utils/desensitization'
	import CharterContractDetails from '@/components/contract/contract-detail-dialog/charter-contract/index.vue'
	import SigningDialog from '@/components/contract/signing/signing-dialog.vue'
	import BatchRetreatRent from '@/components/contract/contract-detail-dialog/charter-contract/batch-retreat-rent.vue'
	import ContractsCancel from '@/components/contract/enterprise-customer-management/contracts-cancel.vue'
	import XEUtils from 'xe-utils'
	import dayjs, {Dayjs} from 'dayjs'
	import {Modal, message} from 'ant-design-vue'
	import {useStore} from '@/store/index'
	import {FormItemRest} from 'ant-design-vue/es/form'
	import {hasApproval} from '@/api/charter-contract'

	const props = withDefaults(
		defineProps<{
			visible: boolean
			type: number
			id: string
			hideDetails?: boolean
			currentSign?: number
			contract?: any
		}>(),
		{
			// 续租2 退1 作废3
			type: 2,
			contract: {
				isApproval: false
			}
		}
	)

	const emit = defineEmits(['update:visible', 'success'])

	// 弹窗配置
	const options = reactive({
		width: '80vw',
		title: '续租',
		maskClosable: false,
		centered: true,
		destroyOnClose: true,
		visible: toRef(props, 'visible'),
		bodyStyle: {padding: '10px'},
		onCancel: () => {
			emit('update:visible', false)
		}
	})

	const grid = ref<VxeGridInstance>()

	const modelRef = reactive<any>({
		tips: '检测到当前合同存在关联的补签合同，请选择本次续租的企业合同！'
	})
	/**
	 * 合同数据
	 */
	const records = ref<any>({})
	const visibles = reactive<any>({
		showDetails: false,
		showRetreatRent: false,
		addCharter: false,
		approvalStatus: ''
	})

	const resubmitId = ref<any>(null)
	const reletId = ref<any>(null)
	const reletIds = ref<any>([])
	const contractIds = ref<any>([])

	const info = reactive({
		id: null,
		name: null
	})

	const params = reactive<any>({
		contractStatus: 2,
		signTypeList: [],
		approvalStatusList: [-1, 3]
	})

	/** 选中企业合同 */
	const selections = ref<any>([])

	const gridOptions = reactive<VxeGridProps>({
		height: 'auto',
		showOverflow: true,
		rowConfig: {
			height: 60,
			isHover: true
		},
		// @ts-ignore
		onCheckboxAll({records}: any) {
			selections.value = records
		},
		onCheckboxChange({records}: any) {
			selections.value = records
		},
		columns: [
			{
				type: 'checkbox',
				width: 60,
				visible: props.type === 3
			},
			{
				minWidth: 180,
				title: '合同编号',
				field: 'contractNo'
			},
			{
				title: '状态',
				width: 120,
				align: 'center',
				slots: {
					default: 'label'
				}
			},
			{
				minWidth: 200,
				title: '企业名称',
				resizable: true,
				slots: {
					default: 'enterpriseName'
				}
			},
			{
				minWidth: 300,
				resizable: true,
				title: '成交方式/签约人/签约时间/包租数量',
				slots: {
					default: 'contract'
				}
			},

			{
				minWidth: 200,
				resizable: true,
				title: '姓名/电话',
				slots: {
					default: 'personal'
				}
			},
			{
				minWidth: 300,
				resizable: true,
				title: '周期/租金/押金/付款方式',
				slots: {
					default: 'cycle'
				}
			},
			{
				title: '操作',
				width: 150,
				align: 'center',
				fixed: 'right',
				slots: {
					default: 'action'
				}
			}
		],
		proxyConfig: {
			props: {
				list: 'data',
				message: 'msg',
				result: 'data'
			},
			ajax: {
				query({page: {currentPage: current, pageSize: size}}) {
					return queryData({...params, current, size})
				}
			}
		}
	})

	const getListF = (page?: any) => {
		grid.value?.commitProxy(page === 1 ? 'reload' : 'query')
	}

	const queryData = async (params: any) => {
		let res: any = []
		res = await getList({
			...params,
			transitionType: 0
		})

		// 审批页面下的 批量操作续租其实是查看父合同
		if (props.contract.isApproval && props.type === 2) {
			res = await getBeforeRenewalList(props.id)
		}

		console.log('🚀 ~ file: batch-operate.vue:287 ~ queryData ~ res:', res)
		if (!res.data || res.data.length === 0) {
			options.onCancel()
		}
		return res
	}

	//操作
	const handlerClick = async (row: any, field: number) => {
		records.value.id = row.id
		records.value.label = row.label
		visibles.approvalStatus = row.approvalStatus

		reletId.value = null

		switch (field) {
			case 0:
				visibles.showDetails = true
				break
			// 批量退租
			case 1:
				// 企业合同如果是驳回或者撤销 则不需要检验
				if (!['2', '4'].includes(row.approvalStatus)) {
					const res = await hasApproval(row.id)

					if (res.data) return message.warning('企业子合同正在审批流（审批中、审批驳回、审批撤销）中，请先完成企业子合同审批')
				}

				visibles.showRetreatRent = true
				break
		}
	}

	const confirm = async () => {
		console.log('🚀 ~ file: batch-operate.vue:270 ~ confirm ~ selections.value:', selections.value)

		try {
			for (const row of selections.value) {
				// 企业合同如果是驳回或者撤销 则不需要检验
				if (!['2', '4'].includes(row.approvalStatus)) {
					const res = await hasApproval(row.id)

					if (res.data) {
						message.warning(
							'合同编号【' +
								(row?.contractNo ? row.contractNo : '--') +
								'】的企业合同存在审批流中的企业子合同，请先完成对应企业子合同审批'
						)
						throw new Error('jay')
					}
				}
			}
		} catch (e) {
			console.log('🚀 ~ file: batch-operate.vue:342 ~ confirm ~ e:', e)
			return
		}

		switch (props.type) {
			// 续租
			case 2:
				try {
					selections.value.forEach((row, index) => {
						if (dayjs(row.enterPriseEndTime).diff(row.endTime, 'day') == 0) {
							message.warning(
								`无法续租,当前选中的第${
									index + 1
								}个合同周期结束日期等于合作周期结束日期,如需续租,请先至【企业库】延长与承租企业合作周期`
							)
							throw new Error()
						}
					})
				} catch (e) {
					return
				}

				reletId.value = props.id
				reletIds.value = selections.value.map(item => item.id)
				// 没有匹配的取第一个
				records.value = XEUtils.clone(selections.value.find(item => item.id === props.id) || selections.value[0], true)
				records.value.signType = 2
				visibles.addCharter = true

				break
			// 作废
			case 3:
				info.id = selections.value.find(item => item.id === props.id)?.id
				info.name = selections.value.find(item => item.id === props.id)?.enterPriseName || selections.value[0].enterPriseName
				contractIds.value = selections.value.map(item => item.id)
				visibles.contractsCancel = true
				break
		}
	}

	const close = () => {
		visibles.showDetails = false
		getListF()
	}

	watch(
		() => props.visible,
		(newVal: boolean) => {
			if (newVal) {
				params.contractPid = props.id
				params.signTypeList = [props.currentSign, 5]
				options.title = props.type === 2 ? '关联续签前合同' : props.type === 1 ? '退租' : '作废'
				modelRef.tips =
					props.type === 2
						? '检测到当前合同存在多个关联的续签前合同，请选择需要查看的企业合同!'
						: props.type === 1
						? '检测到当前合同存在关联的补签合同，请选择本次退租的企业合同！'
						: '检测到当前合同存在关联的补签合同，请选择本次作废的企业合同！'

				grid.value?.refreshColumn()
			}
		}
	)
</script>

<style lang="less" scoped>
	.invOrgs {
		width: 100%;
		height: 40px;
		line-height: 40px;
		background: #fffbe6;
		color: @warning-color;
		border-radius: 2px 2px 2px 2px;
		opacity: 1;
		border: 1px solid #ffe58f;
		padding-left: 16px;
		margin-bottom: 20px;
	}
</style>
